package com.htzy.extrace.ui.main;

import java.util.HashMap;
import java.util.Map;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.ActionBarActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.htzy.extrace.encrypt.encriptTest1;
import com.htzy.extrace.loader.UserInfoLoader;
import com.htzy.extrace.misc.model.UserInfo;
import com.htzy.extrace.net.IDataAdapter;
import com.htzy.extrace.util.Global;
import com.htzy.extrace.util.Utils;

/**
 * 登录
 * @author chenwenyan
 */
public class LoginActivity extends ActionBarActivity implements
		IDataAdapter<UserInfo> {

	private static final String CONFIG_USER = Global.CONFIG_USER;
	// 输入的用户id
	private EditText etUserId;
	// 用户输入的密码
	private EditText etPassword;
	// 登陆页面按钮
	private Button btn_Login;

	private ImageView moImgPhoto;
	private ImageView moImgProgress;
	private LinearLayout moLayoutWelcome;
	private View moViewSlideLine;
	private ImageView moImgSlider;
	private Button moBtnClearUserId;
	private Button moBtnClearPassword;
	private Button moBtnRegister;
	private Button moBtnTraveller;

	public String id;
	public int UID;
	public String PWD;
	// 本地保存文件句柄
	private SharedPreferences sharedPreferences;
	private static UserInfo userInfo = new UserInfo();

	// 声明加密所使用的类
	private encriptTest1 encriptTest1;

	// Members
	private Handler moHandler;
	private boolean mbIsSlidingBack;
	private int miSliderMinX, miSliderMaxX, miLastX;
	private String msRedirectPage;

	// Constant
	public static final int PASSWORD_MIN_LENGTH = 3;
	public static final int LOGIN_SUCCESS = 0; // 登录成功
	public static final int LOGIN_FAILED = 1; // 登录失败
	public static final int LOGIN_SLIDER_TIP = 2; // 登录页面滑块向左自动滑动
	public static final int LOGIN_PHOTO_ROTATE_TIP = 3; // 登录页面加载图片转动

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getSupportActionBar().setDisplayHomeAsUpEnabled(true);
		setContentView(R.layout.activity_logintest);
		sharedPreferences = getSharedPreferences(CONFIG_USER, 0);
		// 读入用户信息配置文件
		InitConfig();

		setHandler();
		initMembers();
		setEventListeners();

		// 如果用户已经登陆，再次点击登陆按钮则提示不用重复登陆
		if (UserOrNot()) {
			Toast.makeText(this, "您已经登陆！无需重复登陆", Toast.LENGTH_LONG).show();
			// finish();
		}

	}

	// 初始化配置
	private void InitConfig() {
		userInfo.setID(sharedPreferences.getInt("UID", 0));
		userInfo.setPWD(sharedPreferences.getString("PWD", null));
		userInfo.setName(sharedPreferences.getString("name", null));
		userInfo.setURull(sharedPreferences.getInt("URull", 0));
		userInfo.setTelCode(sharedPreferences.getString("telCode", null));
		userInfo.setStatus(sharedPreferences.getInt("status", 0));
		userInfo.setDptID(sharedPreferences.getString("dptID", null));
		userInfo.setReceivePackageID(sharedPreferences.getString(
				"receivePackageID", null));
		userInfo.setDelivePackageID(sharedPreferences.getString(
				"delivePackageID", null));
		userInfo.setTransPackageID(sharedPreferences.getString(
				"transPackageID", null));
	}

	// 触摸登录界面收回键盘
	public boolean onTouchEvent(android.view.MotionEvent poEvent) {
		try {
			InputMethodManager loInputMgr = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
			return loInputMgr.hideSoftInputFromWindow(getCurrentFocus()
					.getWindowToken(), 0);
		} catch (Exception e) {
			return false;
		}
	}

	/**
	 * 处理登录状态信息
	 */
	private void setHandler() {
		moHandler = new Handler() {
			@Override
			public void handleMessage(Message poMsg) {
				if (!canLogin()) {
					System.out.println("登陆失败");
					poMsg.what = LOGIN_FAILED;
				} else if (canLogin()) {
					System.out.println("登录成功");
					poMsg.what = LOGIN_SUCCESS;
				}
				switch (poMsg.what)
					{
					case LOGIN_SUCCESS:
						// 登录成功
						Map<String, String> lmExtra = null;
						if (!Utils.isStrEmpty(msRedirectPage)) {
							lmExtra = new HashMap<String, String>();
							lmExtra.put("redirect", msRedirectPage);
						}
						Utils.gotoActivity(LoginActivity.this,
								MainActivity.class, true, lmExtra);
						// Intent intent=new
						// Intent(LoginTest.this,MainActivity.class);
						// startActivity(intent);
						// break;
					case LOGIN_FAILED:
						// 登录失败
						stopLogin();
						Toast.makeText(LoginActivity.this, (String) poMsg.obj,
								Toast.LENGTH_LONG).show();
						break;
					case LOGIN_SLIDER_TIP:
						moImgSlider.layout(miLastX, moImgSlider.getTop(),
								miLastX + moImgSlider.getWidth(),
								moImgSlider.getTop() + moImgSlider.getHeight());
						break;
					case LOGIN_PHOTO_ROTATE_TIP:
						moImgPhoto.setImageBitmap((Bitmap) poMsg.obj);
						break;
					}
			}
		};
	}

	// 实例化控件
	private void initMembers() {
		moImgPhoto = (ImageView) findViewById(R.id.login_img_photo);
		moImgProgress = (ImageView) findViewById(R.id.login_img_progress);
		moLayoutWelcome = (LinearLayout) findViewById(R.id.login_layout_welcome);
		moViewSlideLine = findViewById(R.id.login_view_line);
		etUserId = (EditText) findViewById(R.id.login_edit_userid);
		etPassword = (EditText) findViewById(R.id.login_edit_password);
		moImgSlider = (ImageView) findViewById(R.id.login_img_slide);
		moBtnClearUserId = (Button) findViewById(R.id.login_btn_clear_userid);
		moBtnClearPassword = (Button) findViewById(R.id.login_btn_clear_password);
		mbIsSlidingBack = false;
		miLastX = 0;
		miSliderMinX = 0;
		miSliderMaxX = 0;
	}

	// 设置监听事件
	private void setEventListeners() {
		etUserId.addTextChangedListener(new OnEditUsername());
		etPassword.addTextChangedListener(new OnEditPassword());
		moBtnClearUserId.setOnClickListener(new OnClearEditText());
		moBtnClearPassword.setOnClickListener(new OnClearEditText());
		moImgSlider.setOnClickListener(new OnSliderClicked());
		moImgSlider.setOnTouchListener(new OnSliderDragged());
	}

	/************** 事件处理类 *******************************/
	// 处理用户名编辑事件
	private class OnEditUsername implements TextWatcher {

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
			// 1. 处理右侧清除按钮隐藏/显示
			if (s.length() >= 1)
				moBtnClearUserId.setVisibility(View.VISIBLE);
			else
				moBtnClearUserId.setVisibility(View.GONE);

			// 2. 处理滑块是否可滑动
			initWidgetForCanLogin();
		}

		@Override
		public void afterTextChanged(Editable s) {
		}
	}

	// 处理密码编辑事件
	private class OnEditPassword implements TextWatcher {

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
			// 1. 处理右侧清空按钮显示/隐藏
			if (s.length() >= 1)
				moBtnClearPassword.setVisibility(View.VISIBLE);
			else if (s.length() == 0
					&& moBtnClearPassword.getVisibility() == View.VISIBLE)
				moBtnClearPassword.setVisibility(View.GONE);

			// 2. 处理滑块是否可滑动
			initWidgetForCanLogin();
		}

		private void initWidgetForCanLogin() {
			if (canLogin())
				moImgSlider.setImageResource(R.drawable.ic_arrow_circle_right);
			else
				moImgSlider.setImageResource(R.drawable.ic_ask_circle);
		}

		@Override
		public void afterTextChanged(Editable s) {
		}

	}

	// 清除输入控件中的文字的事件处理
	private class OnClearEditText implements OnClickListener {
		@Override
		public void onClick(View v) {
			switch (v.getId())
				{
				case R.id.login_btn_clear_userid:
					// 如果清除帐号则密码一并清除
					etUserId.setText("");
					etPassword.setText("");
					break;
				case R.id.login_btn_clear_password:
					// 清除已输密码
					etPassword.setText("");
					break;
				default:
					break;
				}
		}
	}

	// 滑动图标点击事件
	private class OnSliderClicked implements OnClickListener {
		public void onClick(View v) {

		}
	}

	// 滑动图标滑动事件
	private class OnSliderDragged implements OnTouchListener {
		@SuppressWarnings("unused")
		@Override
		public boolean onTouch(View v, MotionEvent event) {
			Utils.closeKeybord(etUserId, LoginActivity.this);
			Utils.closeKeybord(etPassword, LoginActivity.this);
			if (canLogin() && !mbIsSlidingBack) {
				if (miSliderMaxX == 0) {
					miSliderMinX = moViewSlideLine.getLeft()
							- moImgSlider.getWidth() / 2;
					miSliderMaxX = moViewSlideLine.getRight()
							- moImgSlider.getWidth() / 2;
				}
				switch (event.getAction())
					{
					case MotionEvent.ACTION_DOWN:
						miLastX = (int) event.getRawX();
					case MotionEvent.ACTION_MOVE:
						int liX = (int) event.getRawX();
						if (liX > miSliderMaxX)
							liX = miSliderMaxX;
						else if (liX < miSliderMinX)
							liX = miSliderMinX;
						if (liX != miLastX) {
							moImgSlider.layout(
									liX,
									moImgSlider.getTop(),
									liX + moImgSlider.getWidth(),
									moImgSlider.getTop()
											+ moImgSlider.getHeight());
							miLastX = liX;
							if (miLastX == miSliderMaxX) {
								// startRotateImg();
								String lsUsername = etUserId.getText()
										.toString();
								String lsPassword = etPassword.getText()
										.toString();
								id = etUserId.getText().toString();
								PWD = etPassword.getText().toString();
								startLogin();
								// TODO 调用借口

							}
						}
						break;
					case MotionEvent.ACTION_UP:
						if ((int) event.getRawX() < miSliderMaxX)
							slideBack();
						break;
					}

			}
			return false;
		}
	}

	// 根据是否可以登录，初始化相关控件
	private void initWidgetForCanLogin() {
		if (canLogin())
			moImgSlider.setImageResource(R.drawable.ic_arrow_circle_right);
		else
			moImgSlider.setImageResource(R.drawable.ic_ask_circle);
	}

	// 判断当前用户输入是否合法，是否可以登录
	private boolean canLogin() {
		Editable loUsername = etUserId.getText();
		Editable loPassword = etPassword.getText();
		id = etUserId.getText().toString();
		PWD = etPassword.getText().toString();
		if (id != null && id.length() > 0 && PWD != null && PWD.length() >= 3) {
			try {
				UID = Integer.parseInt(id);
				// 如果登陆成功
				try {
					checkUserInfo(UID, PWD);
					Toast.makeText(LoginActivity.this, "登陆成功！",
							Toast.LENGTH_SHORT).show();
				} catch (Exception e) {
					Toast.makeText(LoginActivity.this, "登录失败",
							Toast.LENGTH_LONG).show();
				}

			} catch (Exception e) {
				Toast.makeText(LoginActivity.this, "ID请输入数字", Toast.LENGTH_LONG)
						.show();
			}
		}
		return !Utils.isStrEmpty(loUsername)
				&& loPassword.length() >= PASSWORD_MIN_LENGTH;

	}

	// 滑块向会自动滑动
	private void slideBack() {
		new Thread() {
			@Override
			public void run() {
				mbIsSlidingBack = true;
				while (miLastX > miSliderMinX) {
					miLastX -= 5;
					if (miLastX < miSliderMinX)
						miLastX = miSliderMinX;
					Message loMsg = new Message();
					loMsg.what = LOGIN_SLIDER_TIP;
					moHandler.sendMessage(loMsg);
					try {
						Thread.sleep(3);
					} catch (InterruptedException e) {
					}
				}
				mbIsSlidingBack = false;
			}
		}.start();
	}

	// 动画开启
	private void startLogin() {
		Animation loAnimRotate = AnimationUtils.loadAnimation(this,
				R.anim.rotate);
		Animation loAnimScale = AnimationUtils.loadAnimation(this,
				R.anim.login_photo_scale_small);
		// 匀速动画
		LinearInterpolator linearInterpolator = new LinearInterpolator();
		// 加速动画
		// AccelerateInterpolator accelerateInterpolator = new
		// AccelerateInterpolator();
		// 弹跳动画
		// BounceInterpolator bounceInterpolator = new BounceInterpolator();

		loAnimRotate.setInterpolator(linearInterpolator);
		loAnimScale.setInterpolator(linearInterpolator);
		moImgProgress.setVisibility(View.VISIBLE);
		moImgProgress.startAnimation(loAnimRotate);
		moImgPhoto.startAnimation(loAnimScale);

		moImgSlider.setVisibility(View.GONE);
		moViewSlideLine.setVisibility(View.GONE);
		etUserId.setVisibility(View.GONE);
		etPassword.setVisibility(View.GONE);
		moBtnClearUserId.setVisibility(View.GONE);
		moBtnClearPassword.setVisibility(View.GONE);
		moBtnRegister.setVisibility(View.GONE);
		moBtnTraveller.setVisibility(View.GONE);

		moLayoutWelcome.setVisibility(View.VISIBLE);
	}

	// 动画结束
	private void stopLogin() {
		Animation loAnimScale = AnimationUtils.loadAnimation(this,
				R.anim.login_photo_scale_big);
		LinearInterpolator loLin = new LinearInterpolator();
		loAnimScale.setInterpolator(loLin);
		moImgProgress.clearAnimation();
		moImgProgress.setVisibility(View.GONE);
		moImgPhoto.clearAnimation();
		moImgPhoto.startAnimation(loAnimScale);

		moImgSlider.setVisibility(View.VISIBLE);
		moViewSlideLine.setVisibility(View.VISIBLE);
		etUserId.setVisibility(View.VISIBLE);
		etPassword.setVisibility(View.VISIBLE);
		moBtnClearUserId.setVisibility(View.VISIBLE);
		moBtnClearPassword.setVisibility(View.VISIBLE);
		moBtnRegister.setVisibility(View.VISIBLE);
		moBtnTraveller.setVisibility(View.VISIBLE);
		moLayoutWelcome.setVisibility(View.GONE);
	}

	private void showToast(String strToast) {
		Toast.makeText(LoginActivity.this, strToast, Toast.LENGTH_SHORT).show();
	}

	/**
	 * 判断用户是否已经登陆
	 * 
	 * @return 已经登陆返回true，没有登陆返回false
	 */
	public static boolean UserOrNot() {
		if (userInfo.getName() == null || userInfo.getName().length() == 0) {
			return false;
		} else {
			return true;
		}
	}

	/**
	 * 得到已经登陆的用户信息
	 * 
	 * @return 已经登陆返回UserInfo,没有登陆返回new UserInfo();
	 */
	public static UserInfo getUserInfo() {
		if (UserOrNot()) {
			return userInfo;
		} else {
			return new UserInfo();
		}
	}

	/**
	 * 登陆成功将用户信息保存在本地文件中
	 * 
	 * @param userInfo
	 */
	private void initUserInfo() {
		if (userInfo == null) {
			intent();
		}
		SharedPreferences.Editor editor = sharedPreferences.edit();
		editor.putInt("UID", userInfo.getUID());
		editor.putString("name", userInfo.getName());
		editor.putInt("URull", userInfo.getURull());
		editor.putString("telCode", userInfo.getTelCode());
		editor.putInt("status", userInfo.getStatus());
		editor.putString("dptID", userInfo.getDptID());
		editor.putString("receivePackageID", userInfo.getReceivePackageID());
		editor.putString("delivePackageID", userInfo.getDelivePackageID());
		editor.putString("transPackageID", userInfo.getTransPackageID());
		editor.commit();
	}

	private void intent() {
		Intent intent = new Intent(LoginActivity.this, LoginActivity.class);
		startActivity(intent);
		finish();
	}

	protected void checkUserInfo(int UID, String PWD) {
		UserInfoLoader user = new UserInfoLoader(this, this);
		UserInfo user2 = encryptUserInfo(UID, PWD);
		// user.loginTest(user2);
		user.login(user2);
	}

	@Override
	public UserInfo getData() {
		return userInfo;
	}

	public static void setUserInfo(UserInfo userInfo) {
		LoginActivity.userInfo = userInfo;
	}

	@Override
	public void setData(UserInfo userInfo) {
		LoginActivity.userInfo = userInfo;
	}

	@Override
	public void notifyDataSetChanged() {
		// 处理返回来的UserInfo信息,将登陆后的用户信息保存在本地文件中
		initUserInfo();
		ExTraceApplication.setUserInfo(getUserInfo());

		if (UserOrNot()) {
			Intent intent = new Intent(LoginActivity.this, MainActivity.class);
			startActivity(intent);
			finish();
		} else {
			Toast.makeText(LoginActivity.this, "用户ID或密码输入有误！或网络状况不好，请重试！",
					Toast.LENGTH_LONG).show();
		}

	}

	@Override
	public void onBackPressed() {
		Intent intent = new Intent(this, TouristMainActivity.class);
		startActivity(intent);
		finish();
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			Intent intent = new Intent(this, TouristMainActivity.class);
			startActivity(intent);
			finish();
		}
		return false;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// 左上角返回按钮监听
		if (item.getItemId() == android.R.id.home) {
			Intent intent = new Intent(this, TouristMainActivity.class);
			startActivity(intent);
			finish();
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	/**
	 * 对用户输入的ID和PWD进行加密
	 * 
	 * @param id
	 * @param PWD
	 * @return
	 */
	public UserInfo encryptUserInfo(int id, String PWD) {
		String idStr = String.valueOf(id).trim();
		String pwdStr = PWD.trim();
		UserInfo userlogin = new UserInfo();
		encriptTest1 = new encriptTest1();

		String encodeId = encriptTest1.encode(idStr);
		System.out.println(encodeId);
		String encodePwd = encriptTest1.encode(pwdStr);
		System.out.println(encodePwd);
		userlogin.setName(encodeId);
		userlogin.setPWD(encodePwd);
		return userlogin;
	}
}
